<?php
namespace App\Http\Controllers;

use App\Http\Requests\BasicRequest;
use App\Libraries\AppPay;
use App\Models\HouseDistrictCosts;
use App\Models\ShopOrder;
use App\Models\ShopOrderLog;
use App\Models\ShopOrderPayment;
use App\Models\ShopOrderAddress;
use App\Models\Config;
use App\Models\ShopOrderService;
use App\Models\ShopOrderSplit;
use Illuminate\Support\Facades\DB;
use App\Models\Message;
class OrderNotifyController extends CommonController {
	
	/**
	 * 微信回调通知
	 */
	public function wechat(BasicRequest $request){
//		$_POST = '<xml><appid><![CDATA[wxe47fca6036db3677]]></appid>
//<bank_type><![CDATA[CFT]]></bank_type>
//<cash_fee><![CDATA[1]]></cash_fee>
//<fee_type><![CDATA[CNY]]></fee_type>
//<is_subscribe><![CDATA[N]]></is_subscribe>
//<mch_id><![CDATA[1466823402]]></mch_id>
//<nonce_str><![CDATA[16l4wmht7uny9waby7875thp350pkm48]]></nonce_str>
//<openid><![CDATA[ogfbEwi2Ga8iVSOBkkhTZimG2RHM]]></openid>
//<out_trade_no><![CDATA[25112174808531091]]></out_trade_no>
//<result_code><![CDATA[SUCCESS]]></result_code>
//<return_code><![CDATA[SUCCESS]]></return_code>
//<sign><![CDATA[8B518E915C31261A402D27FAD0A6CD05]]></sign>
//<time_end><![CDATA[20170605191020]]></time_end>
//<total_fee>1</total_fee>
//<trade_type><![CDATA[APP]]></trade_type>
//<transaction_id><![CDATA[4009612001201706054433183820]]></transaction_id>
//</xml>';
        logger('微信回调：');
        logger($request->all());
		$app_pay = new AppPay();
		// 验签成功后，返回数组参数
		$post = $app_pay->wechatCheckSign();

		if($post){
			$order_no = substr($post['out_trade_no'],0,17);
			$price = $post['total_fee'] / 100;
			$transaction_id = $post['transaction_id'];
			$status = $this->complete($order_no,$price,$transaction_id);

			// 微信支付回调，成功输出 SUCCESS
			if($status){
				echo 'SUCCESS';
			}else{
				echo 'ERROR';
			}
		}else{
			logger('微信回调算签失败');
			logger($post);
			echo 'ERROR';
		}
	}
	
	/**
	 * 支付宝回调通知
	 */
	public function alipay(BasicRequest $request){
        logger('支付宝回调：');
        logger($request->all());
		$app_pay = new AppPay();
		$sign_success = $app_pay->alipayCheckSign();
		if($sign_success){
			$order_no = $request->input('out_trade_no');
            $order_no = substr($order_no,0,17);
			$price = $request->input('total_amount');
            $trade_no = $request->input('trade_no');
			$status = $this->complete($order_no,$price,$trade_no);
			if($status){
				echo 'success';
			}else{
				echo 'error';
			}
		}else{
			logger('支付宝回调算签失败');
			logger($request->all());
			echo 'error';
		}
	}
	
	/**
	 * @param $order_no string 订单号
	 * @param float $price  商品价格
	 * @param $trade_no string 三方订单号
	 * @return bool
	 * 通用回调处理
	 */
	private function complete($order_no,$price,$trade_no){
        $order_type = ShopOrder::where('order_sn',$order_no)->value('order_type');
        $status = DB::transaction(function () use ($order_no,$price,$trade_no,$order_type) {
            $order_info = ShopOrderPayment::where(['order_sn'=>$order_no])->first();
            $service_mail = Config::key('service_mail')->value('value');
            $confirm_time = Config::key('confirm_time')->value('value');
            $order_confirm_time = Config::key('order_confirm_time')->value('value');
            //订单金额不对直接返回失败;
            if($order_info->pay_amount != $price){
                send_mail($service_mail,'有一条新订单金额有误：'.$order_no.',支付价格：'.$price.'发送消息队列失败,时间：'.time2date());
                throw new \Exception('订单金额有误');
            }
            //更新支付订单的状态
            $update=ShopOrderPayment::where(['order_sn'=>$order_no,'pay_status'=>0])->update(['pay_sn'=>$trade_no,'pay_status'=>1,'updated_at'=>date('Y-m-d H:i:s')]);
            if(!$update){
                throw new \Exception('更新支付单状态失败');
            }

            if($order_type==4) $status = 4;else $status = 2;
            $update = ShopOrder::where(['status' => 1, 'order_sn' => $order_no])->update(['status' => $status, 'updated_at' => date('Y-m-d H:i:s')]);
            if (!$update) {
                throw new \Exception('更新支订单状态失败');
            }

            //更新分成表状态
            $confirm_at = date('Y-m-d'.' 00:00:00',time()+($confirm_time+$order_confirm_time)*3600*24);
            $update = ShopOrderSplit::where(['order_sn'=>$order_no])->update(['status'=>1,'confirm_at'=>$confirm_at]);
            if(!$update){
                throw new \Exception('更新订单分成表失败');
            }
            //发送日志信息
            $details = '成功支付'.$price.'元';
            $update= ShopOrderLog::createOrderLog($order_info->uid,$order_no,$details,'system');
            if(!$update){
                throw new \Exception('发送通知失败');
            }
            $store_id = ShopOrderPayment::where(['order_sn'=>$order_no])->value('store_id');
            if($order_type==4) {
                Message::message_push($store_id, 'service_pay', '您的客户已确认付款，订单号：' . $order_no . '金额'.$price, 1);
                $service=ShopOrderService::where('order_sn',$order_no)->first();
                $param[0] = ShopOrderAddress::where('order_sn',$order_no)->value('mobile');
                $param[1] = $price;
                send_message($service->service_mobile,'付款通知',$param);
            }else{
                Message::message_push($store_id, 'new_order', '您有一条新订单待发货，订单号：' . $order_no . '请及时处理', $order_no, 1);
            }
            return true;
        });
        return $status;

	}
}